//
//  ZAQOAuthViewController.swift
//  ZAQWBDZT
//
//  Created by 赵安庆 on 16/9/21.
//  Copyright © 2016年 zaq. All rights reserved.
//

import UIKit
import SVProgressHUD
let WeiboAppSecret = "2f0c97c40f43488e460b5cf22ff60b13"
let WeiboAppKey = "649405490"
let WeiboRedirect_Uri = "http://www.itcast.cn"

class ZAQOAuthViewController: UIViewController {

    private lazy var webView :UIWebView  = UIWebView()
    override func loadView() {
        super.loadView()
        webView.isOpaque = false
// 设置webview的代理为当前控制器
        webView.delegate = self

        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        requestLogin()
        setupUI()
    }
    private func requestLogin() {

     let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        print(url)
        let  urlRequest = URLRequest(url: URL(string: url)!)
        webView.loadRequest(urlRequest)

    }
   private func setupUI()  {
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancleAction))
 navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自定填充", target: self, action: #selector(autoFillAction))
    title = "微博"
    }
  @objc  private func cancleAction(){
    dismiss(animated: true, completion: nil)
    SVProgressHUD.dismiss()
    }

  @objc  private func autoFillAction(){
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '18913772549';document.getElementById('passwd').value = 'aoao147741..'")
    }
}
//MARK：UIWebViewDelegate
extension ZAQOAuthViewController:UIWebViewDelegate{
// 开始加载请求
    func webViewDidStartLoad(_ webView: UIWebView) {
      SVProgressHUD.show()
    }
//    加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
//    加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {

    }
//    将要加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        判断url是否合法
        guard let url = request.url else {

            print("url加载失败了！")
            return false

        }
        print(url.absoluteString)
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri){
            print("网络请求成功了")
            return true
        }
//  代码执行到此表示是是我们关心的请求地址

//        获取地址栏的详细参数
        if let query = url.query , query.hasPrefix("code=") {
            //  根据光标的结束位置获取子串
           let code = query.substring(from: "code=".endIndex)
            print(code)
            ZAQUserAccountViewModel.sharedUserAccountViewModel.requestAccesstoken(code: code, callBack: { (isSuccess) in

                if isSuccess {
                    //  表示登录成功
                    print("登录成功")
                    //  要等到dismis完成以后在发送切换根视图控制器的操作
                    self.dismiss(animated: false, completion: {
                        //  进入欢迎页面

                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                    })






                }


            })

        }else{
            dismiss(animated: true, completion: nil)
        }
        return false

    }
//        //  通过code获取accesstoken
    
//    func requestAccesstoken(code: String) {
//
//ZAQNetworkTool.sharedTools.requestAccessToken(code: code) { (response, error) in
//    if error != nil{
//        print("网络请求失败\(error)")
//        return
//    }
//    guard let dic = response as? [String: Any] else {
//        print("返回的不是一个正确字典格式")
//        return
//    }
//    //  代码执行到此表示字典格式没有问题
//    let userAccount = ZAQUserAccount(dic: dic)
//    print(userAccount.access_token)
//
//        self.requestUserInfo(userAccount: userAccount)
//    //  代码执行到此,表示用户登录成功
//    userAccount.saveUserAccount()
//
//
//    }
//
//    }
//
//        //  根据accesskon和用户id获取用户信息
//    func requestUserInfo(userAccount: ZAQUserAccount) -> Void {
//
//        ZAQNetworkTool.sharedTools.requestUserInfo(accessToken: userAccount.access_token!, uid: userAccount.uid) { (response, error) in
//
//            if error != nil {
//                print("网络请求异常: \(error)")
//                return
//            }
//
//            //  代码执行到此网络请求成功
//            guard let dic = response as? [String: Any] else {
//                print("你不是一个正确的字典")
//                return
//            }
//
//            let name = dic["name"]
//            let profile_image_url = dic["profile_image_url"]
//
//
//            userAccount.name = name as? String
//            userAccount.profile_image_url = profile_image_url as? String
//
//
//            print(userAccount.name)
//        }
//
//        }

}


